package com.example.smartcity.Controller;

import com.alibaba.fastjson.JSONObject;
import com.example.smartcity.Service.Impl.FileUploadService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping("/api")
public class ImageUploadController {

    private final FileUploadService fileUploadService;

    public ImageUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile files,@RequestParam("uid")String uid) {
        try {
            if (files != null ) {
                fileUploadService.saveImage(files,uid);
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @PostMapping("/uploadsuishoupai")
    public String upload(@RequestParam("files") String files,
                         @RequestParam("names") String names,
                         @RequestParam("content") String content,
                         @RequestParam("title") String title,
                         @RequestParam("uid")String uid) throws SQLException, IOException {
        // 在这里处理上传的文件，例如保存到数据库或存储服务
        Type fileType = new TypeToken<List<byte[]>>() {}.getType();
        Gson gson = new Gson();
        List<byte[]> imgs;
        imgs = gson.fromJson(files, fileType);
        List<String> imgnames = gson.fromJson(names, new TypeToken<List<String>>() {}.getType());
        String textcontent = gson.fromJson(content,String.class);
        String texttitle = gson.fromJson(title,String.class);
        fileUploadService.savesuishoupaiimg(imgs,imgnames,textcontent,texttitle,uid);
        JSONObject map = new JSONObject();
        map.put("message", "文件上传成功");
        map.put("code","200");
        return map.toJSONString();

    }
}